if(NOT EXISTS "@CMAKE_BINARY_DIR@/install_manifest.txt")
  message(FATAL_ERROR "install_manifest.txt not found: @CMAKE_BINARY_DIR@/install_manifest.txt")
endif()

file(STRINGS "@CMAKE_BINARY_DIR@/install_manifest.txt" files)

# 删除文件并收集要检查的目录
set(dirs "")
foreach(f ${files})
  if(EXISTS "${f}")
    message(STATUS "Uninstalling: ${f}")
    file(REMOVE "${f}")
  endif()

  get_filename_component(dir "${f}" DIRECTORY)
  if(dir AND NOT dir STREQUAL "")
    list(FIND dirs "${dir}" idx)
    if(idx EQUAL -1)
      list(APPEND dirs "${dir}")
    endif()
  endif()
endforeach()

# 尝试多轮删除：删除空目录（从叶子向上）
set(changed TRUE)
while(changed)
  set(changed FALSE)
  foreach(d ${dirs})
    if(EXISTS "${d}" AND IS_DIRECTORY "${d}")
      # 列出目录下的非 . 和 .. 条目（包括隐藏文件）
      file(GLOB children RELATIVE "${d}" "${d}/*" "${d}/.[!.]*" "${d}/..?*")
      if(NOT children)
        message(STATUS "Removing empty directory: ${d}")
        file(REMOVE_RECURSE "${d}")  # 目录为空所以安全
        set(changed TRUE)
      endif()
    endif()
  endforeach()
endwhile()